<template>
	<hx-navbar :is-back="false" title="购物车"></hx-navbar>
	<view class="cart-header">
		<!-- 收货地址 -->
		<view @click="toAddress"><u-icon name="map"></u-icon>{{ state.address && state.address.detailAddress ?
			state.address.detailAddress : '请添加收货地址' }}</view>
		<!-- 编辑按钮 -->
		<view><u-button size="mini" type="primary" @click="handleEdit">{{ state.isEdit ? '完成' : '编辑'
		}}</u-button></view>
	</view>
	<view class="cart-container">
		<view class="cart-item" v-if="state.cartList.length > 0">
			<view class="cart-content" v-for="(goods, goodsIndex) in state.cartList" :key="goodsIndex">
				<view v-if="state.isEdit">
					<u-checkbox-group :wrap="true">
						<u-checkbox shape="circle" v-model="goods.checked" @change="cartCheck" :name="goodsIndex">
						</u-checkbox>
					</u-checkbox-group>
				</view>
				<view v-else>
					<u-checkbox-group :wrap="true" v-if="goods.goodsSku && goods.goodsSku.stock > 0">
						<u-checkbox shape="circle" v-model="goods.checked" @change="cartCheck" :name="goodsIndex">
						</u-checkbox>
					</u-checkbox-group>
					<view class="no-stock-warp" v-else>无货</view>
				</view>
				<!-- left -->
				<image :src="goods.picUrl" @click="toGoodsDetail(goods.spuId)" />
				<!-- right -->
				<view class="cart-right" @click="toGoodsDetail(goods.spuId)">
					<view class="name u-line-2"
						:style="{ color: goods.goodsSku && goods.goodsSku.stock > 0 ? '#606266' : '#c0c4cc' }">{{
							goods.spuName
						}}</view>
					<view class="select" v-if="goods.specsInfo">
						<view class="select-text u-line-2" @tap.stop="openSkuPopup(goods)">
							{{ goods.goodsSku ? goods.specsInfo : '规格不存在请重新选择' }}<u-icon name="arrow-down"
								class="u-padding-left-10"></u-icon>
						</view>
					</view>
					<view class="price" v-if="goods.goodsSku">
						<view class="price-text text-price">{{ goods.goodsSku.salesPrice }}</view>
						<vk-data-input-number-box v-if="goods.goodsSku.stock > 0" v-model="goods.quantity" :min="1"
							:max="goods.goodsSku.stock" :step="1" :positive-integer="true" @change="quantityChange"
							:index="goods.id"></vk-data-input-number-box>
					</view>
				</view>
			</view>
		</view>
		<view v-else class="u-margin-20">
			<u-empty text="购物车为空" mode="car">
				<template v-slot:bottom>
					<u-button class="u-margin-top-10" type="primary" size="mini" @click="toPageUrl">去逛逛</u-button>
				</template>
			</u-empty>
		</view>
	</view>
	<!-- 底部全选结算-->
	<view class="cart-footer">
		<view class="cart-footer-warp">
			<view class="cart-footer-left">
				<u-checkbox-group :wrap="true">
					<u-checkbox shape="circle" @change="checkedAll" v-model="state.checkedAll"> 全选 </u-checkbox>
				</u-checkbox-group>
			</view>
			<view class="cart-footer-right" v-if="!state.isEdit">
				<view class="price">
					<text>合计：</text><text class="text-price" style="color: red">{{ state.totalAmount }}</text>
				</view>
				<u-button type="error" :custom-style="state.customStyle" size="medium" shape="circle"
					@click="toSettlement" :disabled="state.checkedList.length <= 0">去结算({{ state.checkedList.length
					}})</u-button>
			</view>
			<view class="cart-footer-right" v-if="state.isEdit">
				<u-button type="error" :custom-style="state.customStyle" size="medium" shape="circle" @click="delCart"
					:disabled="state.checkedList.length <= 0">删除({{ state.checkedList.length }})</u-button>
			</view>
		</view>
	</view>
	<!-- 为你推荐 -->
	<view class="like-title">
		<u-icon name="heart-fill" color="red"></u-icon>
		<text class="u-font-14 u-margin-10">你可能还喜欢</text>
		<u-icon name="heart-fill" color="red"></u-icon>
	</view>
	<WaterfallGoods></WaterfallGoods>
	<vk-data-goods-sku-popup ref="skuPopup" v-model="skuKey" border-radius="20" :localdata="state.goodsSpu"
		:defaultSelect="selectedSku" skuArrName="goodsSkuSpecsValues" skuListName="goodsSkus"
		specListName="goodsSpuSpecs" :mode="skuMode" @open="onOpenSkuPopup" @close="onCloseSkuPopup"
		@add-cart="editCart"></vk-data-goods-sku-popup>
</template>

<script setup lang="ts">
import { onShow, onLoad } from '@dcloudio/uni-app';
import { reactive, ref } from 'vue';
import { getPage, delShoppingCart, editShoppingCart } from '@/api/order/shoppingCart';
import { getById } from '@/api/product/spu';
import { getDefault } from '@/api/user/address';
import { Local } from '@/utils/storage';
import { useGoodsStore } from '@/stores/goods';
// 引入组件
import WaterfallGoods from '@/components/waterfall-goods/index.vue';
import VkDataInputNumberBox from '@/components/vk-data-input-number-box/vk-data-input-number-box.vue';
interface ShoppingCartState {
	customStyle: {
		margin: string;
		padding: string;
	};
	checkedList: any[]; // 更具体化类型
	cartList: any[]; // 更具体化类型
	checkedAll: boolean;
	totalAmount: string;
	isEdit: boolean;
	address: Record<string, unknown>;
	goodsSpu: Record<string, unknown>;
	selectArr: any[];
}

// 定义变量
const storesGoodsStore = useGoodsStore();
const skuPopup = ref();
const skuKey = ref<boolean>(false);
const skuMode = ref<number>(1);
const selectedSku = ref();
const selectedCartId = ref();

const state = reactive<ShoppingCartState>({
	customStyle: {
		margin: '10rpx',
		padding: '20rpx',
	}, // 去结算按钮样式
	checkedList: [], // 已勾选数组
	cartList: [], // 购物车数据
	checkedAll: false, // 全选
	totalAmount: '0', // 合计金额
	isEdit: false, // 编辑按钮
	address: {}, //默认收货地址
	goodsSpu: {},
	selectArr: [],
});
onLoad(() => {
});
// 全选
const checkedAll = (e: any) => {
	if (e.value) {
		state.cartList.forEach((val: any) => {
			val.checked = e.value;
			const exists = state.checkedList.some((obj) => obj.id === val.id);
			if (state.isEdit || val.goodsSku.stock > 0) {
				if (!exists) {
					val.checked = e.value;
					state.checkedList.push(val);
				}
			}
		});
	} else {
		state.checkedList = [];
		state.cartList.forEach((val) => {
			val.checked = e.value;
		});
	}

	computePrice();
};
// 单选
const cartCheck = (e: any) => {
	let cartGoods = state.cartList[e.name];
	cartGoods.checked = e.value;
	if (e.value) {
		state.checkedList.push(cartGoods);
	} else {
		state.checkedList.forEach((val, index) => {
			if (cartGoods.id == val.id) {
				state.checkedList.splice(index, 1);
				return;
			}
		});
	}
	computePrice();
};
const selectedAll = () => {
	if (state.cartList.length <= 0) {
		state.checkedAll = false;
		return;
	}
	// 全选按钮是否选中
	state.checkedAll = state.cartList.every((f: any) => f.checked);
};

//数量改变
const quantityChange = (e: any) => {
	const params = { id: e.index, quantity: e.value };
	editCart(params);
	computePrice();
};
// 计算合计金额
const computePrice = () => {
	selectedAll();
	let amount = 0;
	state.checkedList.forEach((val: any) => {
		if (val.checked && val.goodsSku) {
			amount += val.goodsSku.salesPrice * val.quantity;
		}
	});
	state.totalAmount = amount.toFixed(2);
};

const getCartPage = () => {
	getPage({
		current: 1,
		size: 100,
	}).then((response) => {
		state.cartList = response.data || [];
		state.checkedList = [];
		computePrice();
	});
};
//查询用户默认收货地址
const getDefaultAddress = () => {
	getDefault().then((res) => {
		state.address = res.data;
	});
};
// 删除选中的商品
const delCart = () => {
	if (state.checkedList.length > 0) {
		uni.showModal({
			content: '确认删除吗？',
			cancelText: '我再想想',
			success(res) {
				if (res.confirm) {
					const ids = state.checkedList.map((v) => v.id);
					delShoppingCart(ids).then((res) => {
						getCartPage();
					});
				}
			},
		});
	}
};
const openSkuPopup = (row: any) => {
	selectedCartId.value = row.id;
	getById(row.spuId).then((response) => {
		state.goodsSpu = response.data;
		skuMode.value = 2;
		skuKey.value = true;
		if (row.goodsSku) {
			selectedSku.value = row.goodsSku;
			selectedSku.value.quantity = row.quantity;
		}
	});
};
// sku组件 开始-----------------------------------------------------------
const onOpenSkuPopup = () => {
	console.log('监听 - 打开sku组件');
};
const onCloseSkuPopup = (data: any) => {
	state.selectArr = data;
};
// 添加购物车
const editCart = (row: any) => {
	if (!row.id) {
		row.id = selectedCartId.value;
	}
	editShoppingCart(row).then((res) => {
		getCartPage();
		skuKey.value = false;
	});
};
const toPageUrl = () => {
	uni.$hxRouter.push({ url: '/pages/product/goods-list/index' });
};

// 跳转商品详情
const toGoodsDetail = (id: string) => {
	uni.$hxRouter.push({ url: '/pages/product/goods-detail/index?id=' + id });
};
// 去结算 跳转结算页
const toSettlement = () => {
	storesGoodsStore.setGoodsInfo(state.checkedList);
	uni.$hxRouter.push({ url: '/pages/order/order-confirm/index?createWay=1' }, true);
};

const toAddress = () => {
	uni.$hxRouter.push({ url: '/pages/user/address/index' }, true);
};
const handleEdit = () => {
	state.isEdit = !state.isEdit;

	if (!state.isEdit) {
		// 退出编辑模式时，移除已选中但无库存的商品
		state.checkedList = state.checkedList.filter((item: any) => item.goodsSku.stock > 0);

		// 若不是全选状态，检查是否应设置为全选
		if (!state.checkedAll) {
			const hasUnselectedInStock = state.cartList.some(
				(item: any) => !item.checked && item.goodsSku.stock > 0
			);
			state.checkedAll = !hasUnselectedInStock;
		}
	} else {
		// 进入编辑模式时，若当前为全选，取消无库存商品选中状态
		if (state.checkedAll) {
			let hasNoStock = false;
			state.cartList.forEach((item: any) => {
				if (item.goodsSku.stock <= 0) {
					item.checked = false;
					hasNoStock = true;
				}
			});
			if (hasNoStock) {
				state.checkedAll = false;
			}
		}
	}

	computePrice();
};
onShow(() => {
	if (Local.getToken()) {
		getCartPage();
		getDefaultAddress();
	}
});
</script>

<style scoped lang="scss">
.cart-header {
	display: flex;
	align-items: center;
	padding: 15rpx;
	justify-content: space-between;
	background-color: #fff;
	position: fixed;
	width: 100%;
	right: 0;
	left: 0;
	z-index: 99;
	box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
}

.cart-container {
	padding: 20rpx;
	margin-top: 80rpx;

	.cart-item {
		background-color: rgb(255, 255, 255);
		border-radius: 10rpx;
		margin-bottom: 20rpx;

		.cart-content {
			padding: 20rpx;
			display: flex;
			align-items: center;
			position: relative;

			&::after {
				content: '';
				position: absolute;
				left: 0;
				bottom: 2rpx;
				width: 100%;
				height: 1px;
				background-color: #f0f0f0;
			}

			image {
				width: 160rpx;
				flex: 0 0 160rpx;
				height: 160rpx;
				border-radius: 8rpx;
			}

			.cart-right {
				flex: 1 0 0%;
				height: 100%;
				margin-left: 20rpx;
				display: flex;
				flex-direction: column;
				overflow: hidden;

				.name {
					font-size: 14px;
				}

				.price {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 14rpx;

					.price-text {
						color: red;
						font-size: 16px;
					}
				}

				.select {
					font-size: 12px;
					color: rgb(106, 106, 106);
					margin-top: 10rpx;
					display: flex;
					align-items: center;

					.select-text {
						border-radius: 20rpx;
						padding: 4rpx 14rpx;
						background-color: rgb(248, 248, 248);
					}
				}
			}
		}
	}
}

.cart-footer {
	position: fixed;
	width: 100%;
	left: 0;
	z-index: 2;
	background-color: rgb(255, 255, 255);
	box-sizing: border-box;
	/* #ifndef MP */
	bottom: calc(50px + env(safe-area-inset-bottom));
	/* #endif */
	/* #ifdef MP */
	bottom: 0;

	/* #endif */
	.cart-footer-warp {
		display: flex;
		position: relative;
	}

	.cart-footer-left {
		display: flex;
		align-items: center;
		padding-left: 30rpx;
	}

	.cart-footer-right {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding-right: 10rpx;

		.price {
			padding-right: 10rpx;
		}
	}
}

.like-title {
	display: flex;
	align-items: center;
	justify-content: center;
}

.no-stock-warp {
	padding: 4rpx;
	background-color: #909399;
	border-radius: 10rpx;
	color: #fff;
	font-size: 12px;
}
</style>
